import React, { ReactElement, useEffect } from 'react';
import {
  View,
  Text,
  Image,
  ViewStyle,
  BackHandler,
  TextStyle
} from 'react-native';

import styles from './style';
import Button from '../Button';
import { blackLeft, whiteLeft } from '../../constant/resource';
import navigator from '../../util/navigator';

export enum NavBarType {
  Common,
  Empty
}

export interface NavBarProps {
  title: string;
  backAction?: () => void;
  type?: NavBarType;
  needLine?: boolean;
  style?: ViewStyle;
  rightText?: string;
  rightAction?: () => void;
  rightStyle?: TextStyle;
}

export default ({
  title,
  backAction,
  type = NavBarType.Common,
  needLine = false,
  style,
  rightText,
  rightAction,
  rightStyle
}: NavBarProps): ReactElement => {
  const handleBackButton = (): boolean => {
    if (backAction) {
      backAction();
      return true;
    }
    return false;
  };

  useEffect((): (() => void) => {
    BackHandler.addEventListener('hardwareBackPress', handleBackButton);

    return (): void => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
    };
  }, []);

  return (
    <View
      style={[
        styles.container,
        type === NavBarType.Empty ? styles.writeContainer : {},
        needLine ? {} : styles.noLine,
        style
      ]}
    >
      <Text
        numberOfLines={1}
        style={[
          styles.title,
          type === NavBarType.Empty ? styles.writeTitle : {}
        ]}
      >
        {title}
      </Text>
      <Button
        hitSlop={{ left: 20, top: 20, right: 20, bottom: 20 }}
        style={styles.back}
        onPress={(): void => {
          if (backAction) {
            backAction();
          } else {
            navigator.goBack();
          }
        }}
      >
        <Image
          style={styles.backIcon}
          source={type === NavBarType.Empty ? whiteLeft : blackLeft}
          resizeMode="contain"
        />
        <Text style={styles.backDesc}>返回</Text>
      </Button>
      {rightText && (
        <Button
          hitSlop={{ left: 20, top: 20, right: 20, bottom: 20 }}
          style={styles.right}
          textStyle={[styles.rightText, rightStyle || {}]}
          text={rightText}
          onPress={(): void => {
            if (rightAction) {
              rightAction();
            }
          }}
        />
      )}
    </View>
  );
};
